'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { FileText, Eye, Edit, Calendar } from 'lucide-react';
import Link from 'next/link';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog';

interface BlogStats {
  totalPosts: number;
  publishedPosts: number;
  draftPosts: number;
  totalViews: number;
}

interface BlogPost {
  id: string;
  title: string;
  content: string;
  excerpt: string;
  author: string;
  publishedAt: string;
  updatedAt: string;
  tags: string[];
  status: 'draft' | 'published';
  slug: string;
  coverImage?: string;
}

export default function AdminDashboard() {
  const [stats, setStats] = useState<BlogStats>({
    totalPosts: 0,
    publishedPosts: 0,
    draftPosts: 0,
    totalViews: 0
  });
  const [recentPosts, setRecentPosts] = useState<BlogPost[]>([]);
  const [loading, setLoading] = useState(true);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // 获取认证token
        const token = document.cookie
          .split('; ')
          .find(row => row.startsWith('auth-token='))
          ?.split('=')[1];

        if (!token) {
          console.error('未找到认证token');
          setLoading(false);
          return;
        }

        // 并行获取文章数据和统计数据
        const [postsResponse, statsResponse] = await Promise.all([
          fetch('/api/admin/posts', {
            headers: {
              'Authorization': `Bearer ${token}`,
            },
          }),
          fetch('/api/stats', {
            headers: {
              'Authorization': `Bearer ${token}`,
            },
          })
        ]);

        const postsData = await postsResponse.json();
        const statsData = await statsResponse.json();
        
        if (postsResponse.ok) {
          setRecentPosts(postsData.posts || []);
        }

        if (statsResponse.ok) {
          setStats({
            totalPosts: statsData.overview.totalPosts || 0,
            publishedPosts: statsData.overview.publishedPosts || 0,
            draftPosts: statsData.overview.draftPosts || 0,
            totalViews: statsData.overview.totalViews || 0 // 使用真实的浏览量数据
          });
        }
      } catch (error) {
        console.error('获取数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  const handleDelete = async (postId: string) => {
    setDeletingId(postId);
    try {
      const response = await fetch(`/api/posts/${postId}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        // 删除成功，从列表中移除
        setRecentPosts(recentPosts.filter(post => post.id !== postId));
        // 更新统计数据
        setStats(prev => ({
          ...prev,
          totalPosts: prev.totalPosts - 1,
          publishedPosts: prev.publishedPosts - (recentPosts.find(p => p.id === postId)?.status === 'published' ? 1 : 0),
          draftPosts: prev.draftPosts - (recentPosts.find(p => p.id === postId)?.status === 'draft' ? 1 : 0)
        }));
      } else {
        const errorData = await response.json();
        alert(`删除失败: ${errorData.error || '未知错误'}`);
      }
    } catch (error) {
      console.error('删除文章失败:', error);
      alert('删除文章失败，请稍后重试');
    } finally {
      setDeletingId(null);
    }
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div>
          <h2 className="text-3xl font-bold">仪表板</h2>
          <p className="text-muted-foreground">欢迎来到博客管理后台</p>
        </div>
        <div className="text-center py-8">
          <p>加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-3xl font-bold">仪表板</h2>
        <p className="text-muted-foreground">欢迎来到博客管理后台</p>
      </div>

      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总文章数</CardTitle>
            <FileText className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.totalPosts}</div>
            <p className="text-xs text-muted-foreground">
              包含草稿和已发布文章
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">已发布</CardTitle>
            <Eye className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.publishedPosts}</div>
            <p className="text-xs text-muted-foreground">
              公开可见的文章
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">草稿</CardTitle>
            <Edit className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.draftPosts}</div>
            <p className="text-xs text-muted-foreground">
              待发布的文章
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总浏览量</CardTitle>
            <Calendar className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.totalViews}</div>
            <p className="text-xs text-muted-foreground">
              所有文章的总浏览量
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Recent Posts */}
      <Card>
        <CardHeader>
          <CardTitle>最近文章</CardTitle>
          <CardDescription>最近创建或更新的文章</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {recentPosts.slice(0, 5).map((post) => (
              <div key={post.id} className="flex items-center justify-between p-4 border rounded-lg">
                <div className="space-y-1">
                  <div className="flex items-center space-x-2">
                    <h3 className="font-medium">{post.title}</h3>
                    <Badge variant={post.status === 'published' ? 'default' : 'secondary'}>
                      {post.status === 'published' ? '已发布' : '草稿'}
                    </Badge>
                  </div>
                  <p className="text-sm text-muted-foreground">{post.excerpt}</p>
                  <div className="flex items-center space-x-4 text-xs text-muted-foreground">
                    <span>作者: {post.author}</span>
                    <span>更新: {formatDate(post.updatedAt)}</span>
                  </div>
                </div>
                <div className="flex items-center space-x-2">
                  <Link href={`/blog/${post.slug}`}>
                    <Badge variant="outline">查看</Badge>
                  </Link>
                  <Link href={`/admin/posts/${post.id}/edit`}>
                    <Badge variant="outline">编辑</Badge>
                  </Link>
                  <DeleteConfirmDialog
                    onConfirm={() => handleDelete(post.id)}
                    title={post.title}
                    description={post.excerpt}
                    isLoading={deletingId === post.id}
                    trigger={
                      <button
                        disabled={deletingId === post.id}
                        className="text-destructive hover:text-destructive/80 text-xs px-2 py-1 rounded border border-destructive/20 hover:border-destructive/40 disabled:opacity-50"
                      >
                        {deletingId === post.id ? '删除中...' : '删除'}
                      </button>
                    }
                  />
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
